<template lang="html">
  <div class="package">
    <div class="wrapper">
      <div class="package-left">
        <i class="icon"></i>
      </div>
      <div class="package-right">
        <div class="hreader">
          <h3 class="title">算力充值</h3>
          <div class="info">
            当前账号： <span class="name">{{ userInfo.nickname }}</span> （ <span class="email">{{ userInfo.email }}</span> ）
          </div>
        </div>
        <div class="content">
          <ul class="lists">
            <li class="list" :class="{active: productId == item.id}" v-for="(item, index) in packageList" :key="index" @click="choiceCommodity(item)">
              <h5 class="unit">
                <span class="num">{{item.productTp}}</span>
                算力
              </h5>
              <div class="price-wra">
                <span class="price">{{item.productPrice}}</span>元
              </div>
            </li>
          </ul>

          <div class="other">
            <span class="tit">其他额度:</span>
            <input @input="choiceSpecial" @blur="testingQuota" v-model="specialVal" class="customize" type="text" maxlength="6" placeholder="单次最少购买5个算力"/>
          </div>

          <div class="desc">
            当前选购的算力可以做多少事情？
            <el-popover
              placement="left"
              width="600"
              trigger="hover">
              <div>
                <h4 class="int-title">
                  <span class="num">{{productTp}}</span>算力可以
                </h4>
                <ul class="int-lists">
                  <li class="int-list" v-for="(item, index) in intList" :key="index">
                    <div class="item-left">
                      ·1块{{item.gpu_type}}, {{item.cpu_num}}核CPU, {{item.memory_num}}G内存的配置
                    </div>
                    <div class="item-right">
                      可以运行  <span class="num">{{item.runHours}}</span> 小时
                    </div>
                  </li>
                </ul>
              </div>
              <a class="here int-here" slot="reference">看这里</a>
            </el-popover>
          </div>
          <div class="dot-line"></div>
          <div v-if="!calculateShow" class="calculate-btn"><span @click="calculateShow = !calculateShow">使用算力券</span></div>
          <div v-if="calculateShow" class="calculate-wrap">
            <div class="other">
              <span class="tit">算力券:</span>
              <input
                v-model="ticketNumber"
                class="customize btn-ticket"
                :class="{'ticket-desc-input': checkInputTicket !== 0}"
                type="text"
                maxlength="6"
                @blur="checkTicketNumber(true)"
                @change="ticketInputChange"
                placeholder="请输入六位优惠码"/>
              <button class="search-ticket-btn" @click="_validationCoupons" type="button" name="button">兑换</button>
            </div>
            <div class="ticket-desc desc">
              <span v-if="checkInputTicket === 1" class="ticket-desc-error">请输入优惠码</span>
              <span v-else-if="checkInputTicket === 2" class="ticket-desc-error">请输入六位字母或数字</span>
              <span v-else-if="checkInputTicket === 3" class="ticket-desc-error">你输入的算力券无效</span>
              <span v-else>
                <span v-show="ticketNumber !== '' && showDiscountNumber">
                  你输入的算力券可抵扣<span class="ticket-desc-yellow">{{discountNumber}}</span>元
                </span>
              </span>
            </div>
          </div>
          <!-- <div class="pay-method">
            <h4 class="title">选择支付方式：</h4>
            <div class="pay">
              <i class="pay-by wechart" :class="{active: payWay == 0}" @click="payWaySelect(0)"></i>
              <i class="pay-by alipay" :class="{active: payWay == 1}" @click="payWaySelect(1)"></i>
            </div>
          </div> -->

          <div class="payment">
            <div class="price-info">
              <span class="nature">原价：</span>
              <span class="price-num ori-price">￥{{payAmount}}</span>
            </div>
            <div class="price-info">
              <span class="nature">优惠：</span>
              <span class="price-num ori-price">￥{{discountAmount === 0 ? 0 : '-' + discountAmount}}</span>
            </div>
            <div class="price-info">
              <span class="nature">实付：</span>
              <span class="price-num act-price-box">￥<span class="act-price">{{payAmountFinal}}</span></span>
            </div>
          </div>

          <div class="to-pay">
            <button class="pay-btn" @click="_saveOrderToPay" type="button" name="button">去支付</button>
          </div>
        </div>
        <el-dialog title="微信支付" :visible.sync="wechartShow" @close="payDialogClose">
          <div class="wechart-wra">
            <div class="info">
              <h4 class="title">微信扫码支付</h4>
              <div class="price-wra">
                ￥
                <span class="price">{{payAmountFinal}}</span>
              </div>
              <div class="img-wra">
                <img class="img" :src="wechartQrUrl" alt="qr">
                <span class="txt">中科类脑</span>
              </div>
              <span class="tip">二维码有效时长为2小时，请尽快支付！ </span>
            </div>
            <div class="logo"></div>
          </div>
        </el-dialog>
        <el-dialog title="网上支付提示" width="600px" :visible.sync="alipayShow">
          <div class="alipay-wra">
            <div class="contents">
              <i class="icon"></i>
              <div class="content-info">
                <div class="tit">支付完成前，请不要关闭此支付验证窗口。</div>
                <div class="tit">支付完成后，请根据您支付的情况点击下面的按钮。</div>
              </div>
            </div>
            <div class="btn-wra">
              <button class="can" type="button" name="button" @click="alipayComplete(0)">支付遇到问题</button>
              <button class="sub" type="button" name="button" @click="alipayComplete(1)">支付完成</button>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCalculate, getCalculationPowerConfList, saveOrderToPay, toWeChatPay, toAlipay, getOrderPayStatus, validationCoupons, cebBankPay } from '@/api/order'
import qs from 'qs'

export default {
  data () {
    return {
      packageList: [],
      // 算力商品集合
      specialInfo: {
        selection: false,
        id: '',
        value: 0
      },
      specialVal: '',
      // 其它额度信息
      productId: '',
      // 商品ID
      productNum: '',
      // 商品数量
      productTp: 0,
      // 商品-算力
      payWay: 2,
      // 支付方式  0 --> 微信  1 --> 支付宝  2 --> 瑶瑶支付
      wechartShow: false,
      // 显示微信支付框
      wechartQrUrl: '',
      // 微信二维码路径
      wechartTimer: null,
      // 微信定时查询
      alipayShow: false,
      // 显示支付宝提示框
      payAmount: 0,
      calculateShow: false,
      payAmountFinal: 0,
      // 支付金额
      intList: [],
      checkInputTicket: 0,
      // 扣费规则集合
      ticketNumber: '', // 算力券码
      discountNumber: 0, // 算力券可抵扣值
      discountAmount: 0, // 优惠值
      showDiscountNumber: false // 显示优惠提示
    }
  },
  methods: {
    // 选择商品
    choiceCommodity (item) {
      this.specialInfo.selection = false
      this.specialVal = ''
      this.productId = item.id
      this.productNum = 1
      this.payAmount = Number(item.productPrice).toFixed(2)
      if (this.payAmount < this.discountNumber) {
        this.discountAmount = this.payAmount
      } else {
        this.discountAmount = this.discountNumber
      }
      this.payAmountFinal = (this.payAmount - this.discountAmount).toFixed(2)
      this._getCalculationPowerConfList(item.productTp)
    },
    // 其它额度选择
    choiceSpecial () {
      this.specialVal = this.specialVal.replace(/^[^1-9]/g, '')
      this.specialVal = this.specialVal.replace(/[^\d]/g, '')
      this.productNum = this.specialVal
      this.specialInfo.selection = true
      this.productId = this.specialInfo.id
      this.payAmount = this.specialInfo.value * this.specialVal
      if (this.payAmount < this.discountNumber) {
        this.discountAmount = this.payAmount
      } else {
        this.discountAmount = this.discountNumber
      }
      this.payAmountFinal = (this.payAmount - this.discountAmount).toFixed(2)
      if (this.specialVal && this.specialVal > 0) this._getCalculationPowerConfList(this.specialVal)
    },
    // 检测其它额度数值 不能小于5
    testingQuota () {
      if (this.specialVal === '') {
        return false
      } else if (this.specialVal < 5) {
        this.$message({
          message: '单次最少购买5个算力',
          type: 'warning'
        })
        return false
      } else {
        return true
      }
    },
    // 支付方式选择
    payWaySelect (index) {
      this.payWay = parseInt(index)
    },
    // 支付宝支付完成跳转情况
    alipayComplete (index) {
      if (index === 0) {
        this.alipayShow = false
      } else {
        this.$router.push({
          path: '/order/list'
        })
      }
    },
    payDialogClose () {
      clearInterval(this.wechartTimer)
    },
    // 校验算力券输入框
    checkTicketNumber () {
      const pattern = /^[a-zA-Z0-9]{6}$/
      if (this.ticketNumber === '') {
        this.checkInputTicket = 1
        return false
      } else if (!pattern.test(this.ticketNumber)) {
        this.checkInputTicket = 2
        return false
      } else {
        this.checkInputTicket = 0
        return true
      }
    },
    // 算力券输入框输入变化
    ticketInputChange () {
      this.showDiscountNumber = false
      this.discountNumber = 0
      this.discountAmount = 0
      if (this.payAmount < this.discountNumber) {
        this.discountAmount = this.payAmount
      } else {
        this.discountAmount = this.discountNumber
      }
      this.payAmountFinal = (this.payAmount - this.discountAmount).toFixed(2)
    },
    // 算力下订单购买
    _saveOrderToPay () {
      if (!this.productId || !this.payAmount || !this.productNum) {
        this.$message({
          message: '请选择需要购买的算力数',
          type: 'warning'
        })
        return false
      }
      if (this.specialInfo.selection && !this.testingQuota()) return false
      const data = {
        productId: this.productId,
        num: Number(this.productNum),
        payWay: this.payWay,
        payAmount: this.payAmountFinal,
        discountAmount: this.discountAmount,
        originalPrice: this.payAmount,
        invoiceFlag: 0,
        token: this.userInfo.bitaToken,
        couponsNumber: this.discountAmount > 0 ? this.ticketNumber : '',
        couponsPrice: this.discountAmount
      }
      this.wechartTimer = null
      if (this.payWay === 2) {
        var win = window.open('about:blank', 'newtab')
      }
      saveOrderToPay(data).then(res => {
        if (res.code === 0) {
          if (res.result.orderStatus === '2') {
            this.$router.push({
              path: '/pay/success',
              query: {
                out_trade_no: res.result.orderId,
                total_amount: this.payAmountFinal
              }
            })
          } else {
            if (this.payWay === 0) {
              // 微信支付
              this.wechartShow = true
              this.wechartQrUrl = toWeChatPay(res.result.orderId)
              this.wechartTimer = setInterval(() => {
                this._getOrderPayStatus(res.result.orderId)
              }, 2000)
            } else if (this.payWay === 1) {
              // 支付宝支付
              let w = window.open('/')
              this.alipayShow = true
              w.location.replace(toAlipay(res.result.orderId))
            } else {
              // 瑶瑶支付
              const data = qs.stringify({
                orderId: res.result.orderId,
                token: this.userInfo.bitaToken
              })
              cebBankPay(data).then(res2 => {
                if (res2.code === 0) {
                  this.alipayShow = true
                  win.location = res2.result.payUrl
                }
              })
            }
          }
        } else if (res.code === 22204) {
          this.checkInputTicket = 3
        } else {
          clearInterval(this.wechartTimer)
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 获取订单支付状态
    _getOrderPayStatus (id) {
      const data = qs.stringify({
        orderId: id,
        token: this.userInfo.bitaToken
      })
      getOrderPayStatus(data).then(res => {
        if (res.code === 0 && parseInt(res.result.pay_status) === 1) {
          clearInterval(this.wechartTimer)
          this.wechartTimer = null
          this.$router.push({
            path: '/pay/success',
            query: {
              out_trade_no: res.result.id,
              total_amount: res.result.pay_amount
            }
          })
        }
      })
    },
    // 获取算力商品集合
    _getCalculate () {
      const data = qs.stringify({
        token: this.userInfo.bitaToken,
        productCategory: 1
      })
      getCalculate(data).then(res => {
        if (res.code === 0) {
          res.result && res.result.forEach(item => {
            if (item.productTp !== '1') {
              this.packageList.push(item)
            } else {
              this.specialInfo.id = item.id
              this.specialInfo.value = item.productPrice
            }
          })
          this.choiceCommodity(this.packageList[0])
        } else if (res.code === 60001) {
          this.$router.push({
            path: '/login'
          })
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 获取算力配置扣费规则
    _getCalculationPowerConfList (num) {
      const query = `?number=${num}&token=${this.userInfo.bitaToken}`
      getCalculationPowerConfList(query).then(res => {
        if (res.code === 0) {
          this.productTp = num
          this.intList = [...res.result]
        } else if (res.code === 60001) {
          this.$router.push({
            path: '/login'
          })
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    },
    // 校验算力券
    _validationCoupons () {
      if (!this.checkTicketNumber()) {
        return false
      }
      const data = qs.stringify({
        couponsNumber: this.ticketNumber,
        token: this.userInfo.bitaToken
      })
      this.discountNumber = 0
      validationCoupons(data).then(res => {
        if (res.code === 0) {
          this.showDiscountNumber = true
          this.discountNumber = res.result.price
          this.discountAmount = res.result.price
          if (this.payAmount < this.discountNumber) {
            this.discountAmount = this.payAmount
          } else {
            this.discountAmount = this.discountNumber
          }
          this.payAmountFinal = (this.payAmount - this.discountAmount).toFixed(2)
        } else if (res.code === 22204 || res.code === 22201) {
          this.checkInputTicket = 3
        } else {
          this.$message({ message: res.msg, showClose: true, type: 'error' })
        }
      })
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  mounted () {
    this._getCalculate()
    this._getCalculationPowerConfList(20)
  },
  beforeRouteLeave (to, from, next) {
    if (from.path === '/order') {
      clearInterval(this.wechartTimer)
      this.wechartTimer = null
    }
    next()
  }
}
</script>

<style lang="stylus" scoped>
  .package
    width 100%
    background #fff
    .wrapper
      width 1162px
      margin 0 auto
      padding: 64px 0
      font-size 0
      .package-left
        display inline-block
        width 294px
        text-align right
        vertical-align top
        .icon
          display inline-block
          width 139px
          height 76px
          background url(../../common/image/icon-project/icon-create-edit.png) no-repeat center
          background-size 139px 76px
      .package-right
        display inline-block
        width 868px
        padding-left 32px
        .hreader
          padding-top 36px
          font-size 0
          .title
            display inline-block
            height 40px
            line-height 40px
            padding-right 48px
            font-size 28px
            color #2D323B
            font-family 'PingFangSC-Medium'
            font-weight 600
          .info
            display inline-block
            height 20px
            line-height 20px
            font-size 14px
            color #7F7F7F
        .content
          width 100%
          .lists
            font-size 0
            display flex
            flex-wrap wrap
            justify-content flex-start
            .list
              display inline-block
              width 154px
              height 156px
              background #ffffff
              border-radius 4px
              margin-right 24px
              margin-top 19px
              cursor pointer
              border 2px solid #F0F4F5
              box-sizing border-box
              font-size 0
              &:hover
                border 2px solid #98C7FF
                .price-wra
                  color #ffffff
                  background #2e94f9
              .unit
                height 107px
                padding 36px 0 38px
                line-height 34px
                text-align center
                font-size 14px
                color #001400
                .num
                  padding-right 10px
                  font-size 24px
                  color #2d323b
                  font-weight 600
              .price-wra
                height 48px
                line-height 48px
                background #f0f1f2
                border-radius 0 0 4px 4px
                width 151px
                font-size 16px
                color #2d323b
                text-align center
                transition all .4s
            .list:nth-child(4n)
              margin-left -1px
            .active
              border 2px solid #98C7FF
              .price-wra
                color #ffffff
                background #2e94f9
          .other
            width 100%
            margin-top 60px
            display flex
            .ticket-desc-input
              border-color #f56c6c !important
              outline none
            .tit
              display inline-block
              width 90px
              height 40px
              line-height 40px
              font-size 14px
              color #2d323b
              font-weight 600
            .customize
              display inline-block
              width 416px
              height 40px
              background #fff
              border 1px solid #cccccc
              font-size 12px
              color #63666c
              text-indent 1em
            .btn-ticket
              width 353px
            .search-ticket-btn
              display inline-block
              width 64px
              height 40px
              line-height 40px
              text-align center
              background #F4F4F4
              border none
              font-size 14px
              color #2D323B
              border 1px solid #cccccc
              border-left none
              cursor pointer
              outline none
          .desc
            position relative
            padding 12px 0 24px
            width 505px
            text-align right
            color #63666c
            font-size 12px
            .here
              color #2E94F9
              cursor pointer
          .ticket-desc
            display flex
            justify-content flex-end
            padding-left 90px
            .ticket-desc-yellow
              color #ee6723
            .ticket-desc-error
              color #f56c6c
          .dot-line
            border-top 1px dashed #e6e7e9
            width 690px
          .calculate-btn
            font-size 12px
            line-height 20px
            color #2e94f9
            text-align left
            padding 12px 0 32px
            width 687px
            span
              cursor pointer
          .calculate-wrap
            .other
              margin-top 23px
            .desc
              padding 12px 0 17px
          .pay-method
            width 690px
            padding-bottom 38px
            .title
              font-size 12px
              color #2d323b
              font-weight bold
            .pay
              width 464px
              padding-top 20px
              font-size 0
              .pay-by
                display inline-block
                width 220px
                height 70px
                border 1.5px solid #F0F4F5
                cursor pointer
              .wechart
                margin-right: 24px
                background url(../../common/image/icon/icon-wechart.png) no-repeat 50%
                background-size 133px 44px
              .alipay
                background url(../../common/image/icon/icon-ali.png) no-repeat 50%
                background-size 133px 44px
              .active
                border 1.5px solid #98c7ff
          .payment
            padding-bottom 15px
            .price-info
              width 193px
              padding-bottom 9px
              font-size 0
              .nature
                display inline-block
                width 42px
                height 20px
                line-height 20px
                font-size 14px
                color #2d323b
              .price-num
                display inline-block
                width 150px
                height 20px
                line-height 20px
                text-align right
                font-size 14px
                color #2d323b
              .act-price-box
                font-size 18px
              .act-price
                color #EE6B62
                font-size 18px
          .to-pay
            width 100%
            padding-bottom 20px
            .pay-btn
              display inline-block
              width 210px
              height 40px
              line-height 40px
              text-align center
              background #218cfd
              border-radius 3px
              border none
              font-size 14px
              color #fff
              cursor pointer
  .int-title
    padding: 20px 20px 10px 20px
    line-height 24px
    font-size 16px
    color #001400
    .num
      padding-right 6px
      font-size 18px
      color #fd7f1e
  .int-lists
    padding: 10px 20px 20px 20px
    .int-list
      display flex
      height 49px
      line-height 48px
      border-bottom 1px dashed #ddd
      .item-left
        flex 1
      .item-right
        flex 0 0 180px
        text-align right
        padding-right 10px
  .wechart-wra
    width 660px
    margin 0 auto
    font-size 0
    .info
      display inline-block
      width 220px
      .title
        height 22px
        line-height 22px
        padding-bottom 7px
        font-size 16px
        color #63666c
        text-align center
      .price-wra
        height 28px
        line-height 28px
        font-size 20px
        color #f5a623
        text-align center
      .img-wra
        width 220px
        height 277px
        margin-top 28px
        border 1px solid #ccc
        .img
          display block
          width 218px
          height 218px
          margin 0 auto
        .txt
          display inline-block
          width 100%
          height 20px
          line-height 20px
          padding-top 20px
          text-align center
          font-size 14px
          color #262626
      .tip
        display block
        width 100%
        height 18px
        line-height 18px
        font-size 12px
        color #f5a623
        text-align center
        padding-top 12px
    .logo
      display inline-block
      width 340px
      height 387px
      margin-left 100px
      background url(../../common/image/icon/wechart-introduce.png) no-repeat 50%
      background-size 339px 387px
  .alipay-wra
    width 100%
    .contents
      margin 0 auto
      font-size 0
      text-align center
      .icon
        display inline-block
        width 66px
        height 66px
        background url(../../common/image/icon/icon-ali-show.png) no-repeat 50%
        background-size 66px 66px
        vertical-align top
      .content-info
        display inline-block
        width 60%
        padding-left 28px
        padding-top 10px
        text-align left
        .tit
          height 22px
          line-height 22px
          font-size 12px
          color #262626
    .btn-wra
      display: flex;
      justify-content: center;
      padding-top 50px
      font-size 0
      .can
        display inline-block
        width 102px
        height 30px
        line-height 30px
        text-align center
        font-size 12px
        background #f1f1f2
        border 1px solid #d1d4d8
        border-radius 4px
        color #262626
        cursor pointer
      .sub
        display inline-block
        width 102px
        height 30px
        line-height 30px
        text-align center
        font-size 12px
        margin-left 20px
        background #218cfd
        border 1px solid #218cfd
        border-radius 4px
        color #fff
        cursor pointer
</style>
